package com.taptech.doufu.ui.fragment
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.core.content.ContextCompat
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.taptech.doufu.R
import com.taptech.doufu.constant.Constant
import com.taptech.doufu.model.FilterItemBean
import com.taptech.doufu.model.novel.bean.NovelCategoryBean
import com.taptech.doufu.model.novel.bean.NovelCategoryGroupBean
import com.taptech.doufu.presenter.novel.INovelCategoryView
import com.taptech.doufu.presenter.novel.NovelCategoryPresenter
import com.taptech.doufu.ui.adapter.BaseRecyclerAdappter
import com.taptech.doufu.ui.adapter.FilterItemAdapter
import com.taptech.doufu.ui.adapter.NovelCategoryChildAdapter
import com.taptech.doufu.ui.adapter.OrderItemAdapter
import com.taptech.doufu.util.ScreenUtil
import kotlinx.android.synthetic.main.fragment_category_child.*
import kotlinx.android.synthetic.main.layout_item_child.view.*

class CategoryChildFragment :BaseMvpFragment<NovelCategoryPresenter>(),INovelCategoryView {

    val TAG_LINE_COUNT = 5
    lateinit var adapter:NovelCategoryChildAdapter
    private val countList = mutableListOf<FilterItemBean>()
    private val progressList = mutableListOf<FilterItemBean>()
    private val stateList = mutableListOf<FilterItemBean>()
    private val orderList = mutableListOf<FilterItemBean>()

    private var isShowingFilter = false
    private var isShowingOrder = false
    private var tags = mutableListOf<String>()


    override fun initPresenter() {
        val bean = arguments?.getSerializable(Constant.DATA) as NovelCategoryGroupBean
        if (bean != null) {
            mPresenter = NovelCategoryPresenter(activity!!,this,bean.url)
            tags = bean.sub_tags
            if (tags != null && tags.size > 0) {
                tags.add(0,"全部")
            }
        }
    }

    override fun getLayout(): Int {
        return R.layout.fragment_category_child
    }


    private fun getTagLines():Int {
        if (tags != null && tags.size > 0) {
            return 1
        }
        return 0
        //暂时只显示一行
//        return when {
//            tags.size <= TAG_LINE_COUNT -> 1
//            tags.size <= TAG_LINE_COUNT*2 -> 2
//            else -> 3
//        }
    }

    private fun createTagView(tag:String):TextView{
        val tvTag = TextView(context)
        tvTag.textSize = 14f
        tvTag.setPadding(ScreenUtil.dip2px(context,15f),ScreenUtil.dip2px(context,3f),ScreenUtil.dip2px(context,15f),ScreenUtil.dip2px(context,10f))
        tvTag.text = tag
        if (tag == "全部") {
            tvTag.setTextColor(ContextCompat.getColor(context!!,R.color.text_color_57))
        }else{
            tvTag.setTextColor(ContextCompat.getColor(context!!,R.color.text_color_7))
        }
        tvTag.setOnClickListener {
            setTagUi(tag)
            if (tag == "全部"){
                mPresenter.getNovelCategoryList(true,"")
            }else{
                mPresenter.getNovelCategoryList(true,tag)
            }
        }
        return tvTag
    }

    private fun setTagUi(tag: String) {
        if (layTagContent.childCount > 0) {
            val layLine = layTagContent.getChildAt(0) as LinearLayout
            if (layLine.childCount > 0) {
                for (i in 0 until layLine.childCount) {
                    val child = layLine.getChildAt(i) as TextView
                    if (tag == child.text) {
                        child.setTextColor(ContextCompat.getColor(context!!,R.color.text_color_57))
                    }else{
                        child.setTextColor(ContextCompat.getColor(context!!,R.color.text_color_7))
                    }
                }
            }
        }
        if (layTagContent.childCount > 1) {
            val layLine = layTagContent.getChildAt(1) as LinearLayout
            if (layLine.childCount > 0) {
                for (i in 0 until layLine.childCount) {
                    val child = layLine.getChildAt(i) as TextView
                    if (tag == child.text) {
                        child.setTextColor(ContextCompat.getColor(context!!,R.color.text_color_57))
                    }else{
                        child.setTextColor(ContextCompat.getColor(context!!,R.color.text_color_7))
                    }
                }
            }
        }
    }

    fun setTags() {
        val lines = getTagLines()
        if (lines == 0) {
            laySort.setPadding(0,ScreenUtil.dip2px(context,10f),0,ScreenUtil.dip2px(context,10f))
        }
        //判断一行能否展示完全
        if (lines == 1){
            val lay = LinearLayout(context)
            for (tag in tags) {
                lay.addView(createTagView(tag))
            }
            layTagContent.addView(lay)
        }else if (lines == 2) {
            val lay = LinearLayout(context)
            val lay2 = LinearLayout(context)
            for (index in tags.indices) {
                val tag = tags[index]
                val tvTag = createTagView(tag)
                if (index <= TAG_LINE_COUNT-1) {
                    lay.addView(tvTag)
                }else{
                    lay2.addView(tvTag)
                }
            }
            layTagContent.addView(lay)
            layTagContent.addView(lay2)

        }else{
            val lay = LinearLayout(context)
            val lay2 = LinearLayout(context)
            for (index in tags.indices) {
                val tag = tags[index]
                val tvTag = createTagView(tag)
                if (index%2==0) {
                    lay.addView(tvTag)
                }else{
                    lay2.addView(tvTag)
                }
            }
            layTagContent.addView(lay)
            layTagContent.addView(lay2)
        }



    }

    override fun initView(rootView: View) {
        setTags()
        mRecyclerView.layoutManager = LinearLayoutManager(context)
        adapter = NovelCategoryChildAdapter(context!!)
        mRecyclerView.adapter = adapter
        mRefreshLayout.setOnRefreshListener {
            mPresenter.getNovelCategoryList(true)
        }
        mRefreshLayout.setOnLoadmoreListener {
            mPresenter.getNovelCategoryList(false)
        }
        mRefreshLayout.autoRefresh()

        layFilterBar.setOnClickListener {
            if (isShowingFilter){
                hideFilterDialog()
            }else{
                if (isShowingOrder) {
                    hideOrderDialog()
                }
                showFilterDialog()
            }
        }
        layOrderBar.setOnClickListener {
            if (isShowingOrder){
                hideOrderDialog()
            }else{
                if (isShowingFilter) {
                    hideFilterDialog()
                }
                showOrderDialog()
            }
        }
        countList.add(FilterItemBean("不限",true))
        countList.add(FilterItemBean("20万以下"))
        countList.add(FilterItemBean("20~50万"))
        countList.add(FilterItemBean("50~100万"))
        progressList.add(FilterItemBean("不限",true))
        progressList.add(FilterItemBean("连载"))
        progressList.add(FilterItemBean("完结"))
        stateList.add(FilterItemBean("不限",true))
        stateList.add(FilterItemBean("收费"))
        stateList.add(FilterItemBean("免费"))
        orderList.add(FilterItemBean("综合排序",true))
        orderList.add(FilterItemBean("收藏量"))
        orderList.add(FilterItemBean("综合分"))
        orderList.add(FilterItemBean("最新更新"))
        val countAdapter = FilterItemAdapter(context!!)
        countAdapter.setOnItemClickListener(object :BaseRecyclerAdappter.OnItemClickListener<FilterItemBean>{
            override fun onClick(item: FilterItemBean, position: Int) {
                mPresenter.countPosition = position
                countAdapter.dataList.forEach {
                    it.select = item.name == it.name
                }
                countAdapter.notifyDataSetChanged()
            }

        })
        countAdapter.setData(countList)
        rvCount.layoutManager = GridLayoutManager(context,3)
        rvCount.adapter = countAdapter

        val progressAdapter = FilterItemAdapter(context!!)
        progressAdapter.setOnItemClickListener(object :BaseRecyclerAdappter.OnItemClickListener<FilterItemBean>{
            override fun onClick(item: FilterItemBean, position: Int) {
                mPresenter.progressPosition = position
                progressAdapter.dataList.forEach {
                    it.select = item.name == it.name
                }
                progressAdapter.notifyDataSetChanged()
            }
        })
        progressAdapter.setData(progressList)
        rvProgress.layoutManager = GridLayoutManager(context,3)
        rvProgress.adapter = progressAdapter

        val stateAdapter = FilterItemAdapter(context!!)
        stateAdapter.setOnItemClickListener(object :BaseRecyclerAdappter.OnItemClickListener<FilterItemBean>{
            override fun onClick(item: FilterItemBean, position: Int) {
                mPresenter.statePosition = position
                stateAdapter.dataList.forEach {
                    it.select = item.name == it.name
                }
                stateAdapter.notifyDataSetChanged()
            }
        })
        stateAdapter.setData(stateList)
        rvState.layoutManager = GridLayoutManager(context,3)
        rvState.adapter = stateAdapter

        val orderAdapter = OrderItemAdapter(context!!)
        orderAdapter.setOnItemClickListener(object :BaseRecyclerAdappter.OnItemClickListener<FilterItemBean>{
            override fun onClick(item: FilterItemBean, position: Int) {
                mPresenter.orderPosition = position
                mPresenter.getNovelCategoryList(true)
                orderAdapter.dataList.forEach {
                    it.select = item.name == it.name
                }
                orderAdapter.notifyDataSetChanged()
                hideOrderDialog()
            }
        })
        orderAdapter.setData(orderList)
        rvOrder.layoutManager = LinearLayoutManager(context)
        rvOrder.adapter = orderAdapter

        tvReset.setOnClickListener {
            mPresenter.countPosition = 0
            mPresenter.progressPosition = 0
            mPresenter.statePosition = 0
            for (position in countAdapter.dataList.indices){
                countAdapter.dataList[position].select = position == 0
            }
            countAdapter.notifyDataSetChanged()
            for (position in progressAdapter.dataList.indices){
                progressAdapter.dataList[position].select = position == 0
            }
            progressAdapter.notifyDataSetChanged()
            for (position in stateAdapter.dataList.indices){
                stateAdapter.dataList[position].select = position == 0
            }
            stateAdapter.notifyDataSetChanged()
        }
        tvSure.setOnClickListener {
            mPresenter.getNovelCategoryList(true)
            hideFilterDialog()
        }

        layDialogBg.visibility = View.GONE
        layFilter.visibility = View.INVISIBLE
        layFilterBar.post {
            if (layFilter != null) {
                layFilter.translationY = -layFilter.height.toFloat()
            }
        }

        rvOrder.visibility = View.INVISIBLE
        rvOrder.post {
            rvOrder.translationY = -rvOrder.height.toFloat()
        }

        layDialogBg.setOnClickListener {
            if (isShowingFilter){
                hideFilterDialog()
            }
            if (isShowingOrder){
                hideOrderDialog()
            }
        }


    }


    @SuppressLint("WrongConstant")
    private fun showOrderDialog() {
        isShowingOrder = true
        rvOrder.visibility = View.VISIBLE
        val animator = ObjectAnimator.ofFloat(rvOrder,"translationY",-rvOrder.height.toFloat(),0f)
        animator.start()
        layDialogBg.visibility = View.VISIBLE
        val arrowAnimator = ObjectAnimator.ofFloat(ivOrderArrow,"rotation",0f,180f)
        arrowAnimator.start()
    }

    private fun hideOrderDialog() {
        isShowingOrder = false
        val animator = ObjectAnimator.ofFloat(rvOrder,"translationY",0f,-rvOrder.height.toFloat())
        animator.start()
        layDialogBg.visibility = View.GONE

        val arrowAnimator = ObjectAnimator.ofFloat(ivOrderArrow,"rotation",180f,0f)
        arrowAnimator.start()
    }


    private fun showFilterDialog(){
        isShowingFilter = true
        layFilter.visibility = View.VISIBLE
        val animator = ObjectAnimator.ofFloat(layFilter,"translationY",-layFilter.height.toFloat(),0f)
        animator.start()
        layDialogBg.visibility = View.VISIBLE


        val arrowAnimator = ObjectAnimator.ofFloat(ivFilterArrow,"rotation",0f,180f)
        arrowAnimator.start()
    }

    private fun hideFilterDialog() {
        isShowingFilter = false
        val animator = ObjectAnimator.ofFloat(layFilter,"translationY",0f,-layFilter.height.toFloat())
        animator.start()
        layDialogBg.visibility = View.GONE

        val arrowAnimator = ObjectAnimator.ofFloat(ivFilterArrow,"rotation",180f,0f)
        arrowAnimator.start()
    }




    override fun getNovelCategoryListResult(isRefresh: Boolean, list: MutableList<NovelCategoryBean>) {
        try {
            if (isRefresh){
//                tvCount.text = "共${mPresenter.total}个内容"
                if (list.size == 0) {
                    layNone.visibility = View.VISIBLE
                }else{
                    layNone.visibility = View.GONE
                }
                adapter.setData(list)
                mRefreshLayout.finishRefresh(500)
            }else{
                if (list.size > 0) {
                    adapter.addData(list)
                }
                mRefreshLayout.finishLoadmore(500)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    companion object{
        fun newInstance(groupBean: NovelCategoryGroupBean):CategoryChildFragment{
            val fragment = CategoryChildFragment()
            val bundle = Bundle()
            bundle.putSerializable(Constant.DATA,groupBean)
            fragment.arguments = bundle
            return fragment
        }
    }

}